package com.demo.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.demo.entity.User;

public class HelloController implements Servlet {

	List<User> users;
	Integer i = 0;
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		users = null;
	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		System.out.println("init方法，只在servlet第一次被访问的时候执行一次！！");
		System.out.println(config.getInitParameter("contextLocation"));
		
	}

	//早起的servlet版本，还有doGet()和doPost()，service()处理任何请求
	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		res.setContentType("text/html;charset=utf-8");
		
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		
		PrintWriter out = response.getWriter();
		
		//在servlet中如何使用session
		HttpSession session = request.getSession();
		
		session.setAttribute("username", "tom");
		out.print(session.getAttribute("username"));
		out.print(session.getId());
		
		response.sendRedirect(request.getContextPath()+"/admin/index.html"); // 正确姿势 ： 应用名/目标资源
		
		
		//路径开头加了/，绝对路径，参照路径就是网站根域名 http://localhost:8080 会忽略我们的应用path
		//路径开头没有加/，相对路径，参照路径就是当前你的位置
	}
	
	
}
